package com.zrb.mobile;

import org.apache.http.Header;

import com.google.gson.Gson;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.zrb.mobile.adapter.model.RegisterDto;
import com.zrb.applib.utils.AppSetting;
import com.zrb.mobile.utility.CommonUtil;
import com.zrb.mobile.utility.Tip;
import com.zrb.mobile.utility.ZrbRestClient;

import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

public class User_registerphoneFragment extends Fragment implements OnClickListener,
		OnFocusChangeListener, TextWatcher {

	ImageView btnAccountclear,btnphoneclear, btnPwdclear,btnshowPwd;
	View next_line;
	EditText editTextphone;
	EditText editTextCode;
	TextView mbtn_nextstep,mbtn_verifycode,mTitle;
	
	Button changephone;
	Tip progTip;
    boolean isShow=false;
    View RootView;
  	private String phoneNum,oldphoneNum;
  	
  	boolean isChangephone=false;
  	
  	
  	private TextView phoneNumstr;
  	MyCount mc;
	/*@Override
	protected void onCreate(Bundle bundle) {
		super.onCreate(bundle);

 		setContentView(R.layout.u_center_registerphone);
 		if (bundle != null)
			restoreSelf(bundle);
		else {
			isChangephone=this.getIntent().getBooleanExtra("changephone", false);
			oldphoneNum=this.getIntent().getStringExtra("phone");
		}
 		initView();
	}*/
 
/*	@Override
	protected  void onSaveInstanceState(Bundle outState) {
       super.onSaveInstanceState(outState);
       outState.putBoolean("changephone", false);//("changephone", mtitle);
       outState.putString("phone", oldphoneNum);
    }

   private void restoreSelf(Bundle savedInstanceState) {
	   isChangephone = savedInstanceState.getBoolean("changephone");
	   oldphoneNum = savedInstanceState.getString("phone");
   }*/
	
  	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {	
		//return inflater.inflate(R.layout.u_center_registerstep1, null);	
		
	 	View view = inflater.inflate(R.layout.u_center_registerphone, container, false);
	 	RootView=view;
		initView();
 		return RootView;
	}		
  	
   protected void initView() {
  		//super.initView();
  	
	  
	/* 	
	 	changephone=(Button)this.findViewById(R.id.changephone_btn);
	 	changephone.setVisibility(isChangephone ? View.VISIBLE:View.GONE) ;
	 	changephone.setOnClickListener(this);
	 	
	 	phoneNumstr=(TextView)this.findViewById(R.id.txt_phonenum);
	 	if(isChangephone) phoneNumstr.setText("当前手机号："+oldphoneNum);*/
	 	
		btnAccountclear = (ImageView) RootView.findViewById(R.id.phone_btn_clean);
		btnAccountclear.setOnClickListener(this);
		
		editTextphone = (EditText) RootView.findViewById(R.id.edit_phone);
		editTextphone.setOnFocusChangeListener(this);
		editTextphone.addTextChangedListener(onPhoneTextChanged);
		
		editTextCode = (EditText) RootView.findViewById(R.id.edit_verifyCode);
  
		mbtn_nextstep=(TextView)RootView.findViewById(R.id.btn_nextstep);
		mbtn_nextstep.setEnabled(false);
		mbtn_nextstep.setOnClickListener(this);
 	
		mbtn_verifycode=(TextView)RootView.findViewById(R.id.btn_validate_Code);
		mbtn_verifycode.setEnabled(false);
		mbtn_verifycode.setOnClickListener(this);
		//this.findViewById(R.id.button_register).setOnClickListener(this);
	/*    View lefticon= this.findViewById(R.id.title_left_root);
		lefticon.setOnClickListener(this);*/
		
		next_line = RootView.findViewById(R.id.next_line);
 	}
 
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {

		case R.id.title_left_root:
			//this.finish();
			break;
 
		case R.id.phone_btn_clean:
			this.editTextphone.setText("");
			break;
		case R.id.btn_nextstep:
			user_register();
			break;
		case R.id.btn_validate_Code:
			//user_register();
			mbtn_verifycode.setEnabled(false);
			checkPhone();
 			break;
		case R.id.changephone_btn:
			user_register();
			break;
 		}
 	}
 	
	 private void initNotify(String msg){
		 
		 
	 }

	private boolean isPhoneOk(boolean isHite,boolean isSubmit){
		
		if (TextUtils.isEmpty(this.editTextphone.getText())) {
			if(isSubmit) initNotify("请输入正确的手机号");
			return false;
 		}
 		if(!CommonUtil.isMobileNO(this.editTextphone.getText().toString().replace(" ", "")))//CommonUtil.isMobileNO(this.editTextphone.getText()
		{
 			if(isHite) initNotify("请输入正确的手机号");
			return false;
		}
 		phoneNum=this.editTextphone.getText().toString().replace(" ", "");
		return true;
	}
	
	
	/*定义一个倒计时的内部类*/  
    class MyCount extends CountDownTimer {     
        public MyCount(long millisInFuture, long countDownInterval) {     
            super(millisInFuture, countDownInterval);     
        }     
        @Override     
        public void onFinish() { 
        	mbtn_verifycode.setEnabled(true);
        	mbtn_verifycode.setText("获取验证码");        
        }     
        @Override     
        public void onTick(long millisUntilFinished) {     
        	mbtn_verifycode.setText("请等待(" + millisUntilFinished / 1000 + ")秒");     
           // Toast.makeText(NewActivity.this, millisUntilFinished / 1000 + "", Toast.LENGTH_LONG).show();//toast有显示时间延迟       
        }    
    }     
	//register/checkMobileRegister?mobile=13720202020
    private void checkPhone(){
    	
    	if(!isPhoneOk(true,true)) return ;
    	RequestParams param = new RequestParams();
		param.put("mobile", phoneNum);
 		ZrbRestClient.post("register/checkMobileRegister", param,
				new AsyncHttpResponseHandler() {
					@Override
					public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {
   						initNotify(User_registerphoneFragment.this.getString(R.string.error_net_loadfail));
					}

					@Override
					public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
  					   String results = new String(arg2);
  					   CommonUtil.InfoLog("checkMobileRegister", results);
						try {
							  Gson gson = new Gson();
							  RegisterDto tmpDto = gson.fromJson(results,	RegisterDto.class);
							  if(tmpDto.res == 1){
 								getvalidateCode();
						      }
						      else{
						        initNotify(tmpDto.msg);
							  }
 						   } catch (Exception e) {
 							initNotify(User_registerphoneFragment.this.getString(R.string.error_serverdata_loadfail));
						}
					}
				});
    }
    
 	private void getvalidateCode(){
 		
 		if(!isPhoneOk(true,true)) return ;
 		RequestParams param = new RequestParams();
		param.put("mobile", phoneNum);
		 
		String requestUrl=isChangephone ?"user/sendModifyMobileAuthCode":"register/sendSMSRegister";
		if(isChangephone) 	param.put("zrb_front_ut", AppSetting.curUser.zrb_front_ut);
		ZrbRestClient.post(requestUrl, param,
				new AsyncHttpResponseHandler() {

					@Override
					public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {
   						initNotify(User_registerphoneFragment.this.getString(R.string.error_net_loadfail));
					}

					@Override
					public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
   					   String results = new String(arg2);
 						try {
 							Gson gson = new Gson();
 							RegisterDto tmpDto = gson.fromJson(results,	RegisterDto.class);
 							if(tmpDto.res==1){
 								if(mc==null)
 						 			mc = new MyCount(60000, 1000);  
 						         mc.start();
 							}
 							else 
 						        initNotify(tmpDto.msg);
  						 } catch (Exception e) {
 							initNotify(User_registerphoneFragment.this.getString(R.string.error_serverdata_loadfail));
 						}
 					}
				});
	}
	
	private void user_register() {
	 
		if (TextUtils.isEmpty(this.editTextCode.getText())) {
			initNotify("校验码不能为空");
			return;
		}
		if(!isPhoneOk(true,true)) return ;
 		//showloading();
  
		String url = String.format("%1$s?mobile=%2$s&smsCode=%3$s",
			            	isChangephone ? "user/updateAppUserPhone"
						                  : "register/checkSMSRegister", phoneNum,this.editTextCode.getText().toString());
  		if(isChangephone)  url+="&zrb_front_ut="+AppSetting.curUser.zrb_front_ut;
  		
  		Log.e("url", url);
 		ZrbRestClient.get(url, null,
				new AsyncHttpResponseHandler() {

					@Override
					public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {
						// TODO Auto-generated method stub
						progTip.Dismiss();
						initNotify(User_registerphoneFragment.this.getString(R.string.error_net_loadfail));
					}

					@Override
					public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
						// TODO Auto-generated method stub
						progTip.Dismiss();
						String results = new String(arg2);
 						try {
 							Gson gson = new Gson();
 							RegisterDto tmpDto = gson.fromJson(results,	RegisterDto.class);
 							
 							if(tmpDto.res==1){
  								/*if(isChangephone){
  									Intent data=new Intent();
 									data.putExtra("phonenum", phoneNum);
 									User_registerphoneFragment.this.setResult(android.app.Activity.RESULT_OK, data);
 									User_registerphoneFragment.this.finish();
 									CommonUtil.showToast("更改成功", User_registerphoneFragment.this);
  									if(mc!=null) mc.cancel();
 									return;
 								}*/
 							 
 							/*   Intent it = new Intent(User_registerphoneFragment.this.getActivity(), User_registername.class);
 							   it.putExtra("phonenum", phoneNum);
 							   it.putExtra("smscode", tmpDto.data);
 			 			       startActivity(it);
 			 			       if(mc!=null) mc.cancel();*/
 							}
 							else
 								initNotify(tmpDto.msg);

						} catch (Exception e) {
							initNotify(User_registerphoneFragment.this.getString(R.string.error_serverdata_loadfail));
 						}
 					}
				});
 	}
 
	@Override
	public void onFocusChange(View v, boolean hasFocus) {
		// TODO Auto-generated method stub
		if (v.getId() == R.id.edit_phone) {
			if (hasFocus && editTextphone.getText().length() != 0)
				btnAccountclear.setVisibility(View.VISIBLE);
			else
			{
				btnAccountclear.setVisibility(View.INVISIBLE);
//				if(isPhoneOk(true,false)) { 
//					mbtn_nextstep.setEnabled(true);
//					mbtn_verifycode.setEnabled(true);
//				}
//				else  { 
//					mbtn_nextstep.setEnabled(false);
//					mbtn_verifycode.setEnabled(false);
//				}
			}
 		}  
	}
  

	private TextWatcher onPhoneTextChanged = new TextWatcher() {

		@Override
		public void afterTextChanged(Editable s) {

		}

		@Override
		public void beforeTextChanged(CharSequence s, int start, int count,
				int after) {

		}

		@Override
		public void onTextChanged(CharSequence s, int start, int before,
				int count) {
			
			if(s.length() == 13) { 
				mbtn_nextstep.setEnabled(true);
				mbtn_verifycode.setEnabled(true);
				changephone.setEnabled(true);
				next_line.setBackgroundColor(getResources().getColor(R.color.login_name_password));
			}
			else  { 
				mbtn_nextstep.setEnabled(false);
				mbtn_verifycode.setEnabled(false);
				changephone.setEnabled(false);
				next_line.setBackgroundColor(getResources().getColor(R.color.white));
			}
			
			if (editTextphone.getText().length() == 0)
				btnAccountclear.setVisibility(View.INVISIBLE);
			else
				btnAccountclear.setVisibility(View.VISIBLE);
			
		    String contents = s.toString();
			int length = contents.length();
			if (length == 4) {
				if (contents.substring(3).equals(" ")) { // -
					contents = contents.substring(0, 3);
					editTextphone.setText(contents);
					editTextphone.setSelection(contents.length());
				} else { // +
					contents = contents.substring(0, 3) + " "+ contents.substring(3);
					editTextphone.setText(contents);
					editTextphone.setSelection(contents.length());
				}
			} else if (length == 9) {
				if (contents.substring(8).equals(" ")) { // -
					contents = contents.substring(0, 8);
					editTextphone.setText(contents);
					editTextphone.setSelection(contents.length());
				} else {// +
					contents = contents.substring(0, 8) + " "+ contents.substring(8);
					editTextphone.setText(contents);
					editTextphone.setSelection(contents.length());
				}
			}
		}
	};
	
	@Override
	public void afterTextChanged(Editable arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void beforeTextChanged(CharSequence s, int start, int count,
			int after) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onTextChanged(CharSequence s, int start, int before, int count) {
		// TODO Auto-generated method stub
		if (editTextphone.getText().length() == 0)
			btnPwdclear.setVisibility(View.INVISIBLE);
		else
			btnPwdclear.setVisibility(View.VISIBLE);
	}
 	
 
}
